package cn.always.xiajia.framework.rpc.core.fegin;

import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import cn.always.xiajia.framework.common.config.RpcProperties;
import cn.always.xiajia.framework.common.config.SecurityProperties;
import cn.always.xiajia.framework.common.web.WebFrameworkUtils;
import cn.hutool.core.codec.Base64;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;

/**
 * 透传数据给feign
 * 
 * @author xgj
 *
 */
@RequiredArgsConstructor
public class RfqRequestInterceptor implements RequestInterceptor {

	private final SecurityProperties securityProperties;

	private final RpcProperties rpcProperties;

	@Override
	public void apply(RequestTemplate template) {
		// 从RequestContextHolder中获取HttpServletRequest
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		// 获取RequestContextHolder中的信息
		Map<String, String> headers = getHeaders(request);

		// 判断是否前端模拟访问rpc
		if (!headers.containsKey(rpcProperties.getRpcHeader().toLowerCase())) {
			template.header(rpcProperties.getRpcHeader(), Base64.encode(rpcProperties.getRpcHeaderSecret().getBytes()));
		}

		// 放入feign的RequestTemplate中
		for (Map.Entry<String, String> entry : headers.entrySet()) {
			if (securityProperties.getTokenHeader().equalsIgnoreCase(entry.getKey())) {
				template.header(entry.getKey(), entry.getValue());
			} else if (WebFrameworkUtils.REQUEST_ATTRIBUTE_LOGIN_USER_ID.equalsIgnoreCase(entry.getKey())) {
				template.header(entry.getKey(), entry.getValue());
			} else if (WebFrameworkUtils.REQUEST_ATTRIBUTE_LOGIN_USER_CODE.equalsIgnoreCase(entry.getKey())) {
				template.header(entry.getKey(), entry.getValue());
			} else if (WebFrameworkUtils.REQUEST_ATTRIBUTE_LOGIN_USER_NAME.equalsIgnoreCase(entry.getKey())) {
				template.header(entry.getKey(), entry.getValue());
			} else if (WebFrameworkUtils.REQUEST_ATTRIBUTE_LOGIN_USER_TYPE.equalsIgnoreCase(entry.getKey())) {
				template.header(entry.getKey(), entry.getValue());
			}
		}
	}

	/**
	 * 获取原请求头
	 */
	private Map<String, String> getHeaders(HttpServletRequest request) {
		Map<String, String> map = new LinkedHashMap<>();
		Enumeration<String> enumeration = request.getHeaderNames();
		if (enumeration != null) {
			while (enumeration.hasMoreElements()) {
				String key = enumeration.nextElement();
				String value = request.getHeader(key);
				map.put(key, value);
			}
		}
		return map;
	}

}
